<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户管理</h1>
        <p class="page-subtitle">管理系统中的所有用户账户</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
        <el-button @click="exportUsers">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalUsers }}</div>
              <div class="stats-label">总用户数</div>
            </div>
            <el-icon class="stats-icon"><User /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.activeUsers }}</div>
              <div class="stats-label">活跃用户</div>
            </div>
            <el-icon class="stats-icon"><UserFilled /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.todayNew }}</div>
              <div class="stats-label">今日新增</div>
            </div>
            <el-icon class="stats-icon"><TrendCharts /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-number">{{ stats.disabledUsers }}</div>
              <div class="stats-label">已禁用</div>
            </div>
            <el-icon class="stats-icon"><Lock /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索用户名、姓名、邮箱"
            style="width: 200px"
            clearable
            @keyup.enter="loadUsers"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select v-model="filterForm.role" placeholder="选择角色" style="width: 120px" clearable>
            <el-option label="学生" value="student" />
            <el-option label="组织者" value="organizer" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" style="width: 120px" clearable>
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loadUsers">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>用户列表</span>
          <div class="table-actions">
            <el-button
              type="success"
              size="small"
              :disabled="selectedUsers.length === 0"
              @click="batchEnable"
            >
              批量启用
            </el-button>
            <el-button
              type="warning"
              size="small"
              :disabled="selectedUsers.length === 0"
              @click="batchDisable"
            >
              批量禁用
            </el-button>
            <el-button
              type="danger"
              size="small"
              :disabled="selectedUsers.length === 0"
              @click="batchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="users"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="用户信息" width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.avatar" :size="40">
                {{ row.realName?.charAt(0) || row.username?.charAt(0) }}
              </el-avatar>
              <div class="user-details">
                <div class="username">{{ row.username }}</div>
                <div class="real-name">{{ row.realName || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
        
        <el-table-column prop="phone" label="联系电话" width="120" />
        
        <el-table-column label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)" size="small">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="学院/组织" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.college || row.organization || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="活动数量" width="100" align="center">
          <template #default="{ row }">
            <span class="activity-count">{{ row.activityCount || 0 }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
              {{ row.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="注册时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createdAt, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        
        <el-table-column prop="lastLoginAt" label="最后登录" width="120">
          <template #default="{ row }">
            {{ row.lastLoginAt ? formatDate(row.lastLoginAt, 'MM-DD HH:mm') : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewUser(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="editUser(row)">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="row.status === 'active' ? 'disable' : 'enable'">
                    {{ row.status === 'active' ? '禁用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="resetPassword">
                    重置密码
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        
        <template #empty>
          <el-empty description="暂无用户数据" />
        </template>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsers"
          @current-change="loadUsers"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="600px"
      @close="resetUserForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="!!editingUser" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
                <el-option label="学生" value="student" />
                <el-option label="组织者" value="organizer" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="userForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="正常" value="active" />
                <el-option label="禁用" value="disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col v-if="!editingUser" :span="24">
            <el-form-item label="初始密码" prop="password">
              <el-input v-model="userForm.password" type="password" placeholder="请输入初始密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="saving">
          {{ editingUser ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="用户详情" width="500px">
      <div v-if="selectedUser" class="user-detail">
        <div class="detail-avatar">
          <el-avatar :src="selectedUser.avatar" :size="80">
            {{ selectedUser.realName?.charAt(0) || selectedUser.username?.charAt(0) }}
          </el-avatar>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">{{ selectedUser.username }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ selectedUser.realName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ selectedUser.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedUser.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag :type="getRoleType(selectedUser.role)" size="small">
              {{ getRoleText(selectedUser.role) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedUser.status === 'active' ? 'success' : 'danger'" size="small">
              {{ selectedUser.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学院/组织">{{ selectedUser.college || selectedUser.organization || '-' }}</el-descriptions-item>
          <el-descriptions-item label="活动数量">{{ selectedUser.activityCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ formatDate(selectedUser.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="最后登录">{{ selectedUser.lastLoginAt ? formatDate(selectedUser.lastLoginAt) : '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils'
import api from '@/utils/api'
import {
  Plus,
  Download,
  Search,
  Refresh,
  ArrowDown,
  User,
  UserFilled,
  TrendCharts,
  Lock
} from '@element-plus/icons-vue'

const loading = ref(false)
const saving = ref(false)
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const editingUser = ref(null)
const selectedUser = ref(null)
const selectedUsers = ref([])

const userFormRef = ref()

const users = ref([])
const stats = reactive({
  totalUsers: 0,
  activeUsers: 0,
  todayNew: 0,
  disabledUsers: 0
})

const filterForm = reactive({
  keyword: '',
  role: '',
  status: '',
  dateRange: []
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const userForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  role: '',
  status: 'active',
  password: ''
})

const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入初始密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const getRoleType = (role) => {
  const typeMap = {
    student: 'primary',
    organizer: 'success',
    admin: 'danger'
  }
  return typeMap[role] || ''
}

const getRoleText = (role) => {
  const textMap = {
    student: '学生',
    organizer: '组织者',
    admin: '管理员'
  }
  return textMap[role] || role
}

const loadStats = async () => {
  try {
    const response = await api.get('/admin/users/stats')
    Object.assign(stats, response.data.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadUsers = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.size,
      keyword: filterForm.keyword,
      role: filterForm.role,
      status: filterForm.status,
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1]
    }
    
    const response = await api.get('/admin/users', { params })
    const data = response.data.data
    
    users.value = data.list || []
    pagination.total = data.total || 0
    
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    role: '',
    status: '',
    dateRange: []
  })
  pagination.page = 1
  loadUsers()
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const viewUser = (user) => {
  selectedUser.value = user
  showDetailDialog.value = true
}

const editUser = (user) => {
  editingUser.value = user
  Object.assign(userForm, {
    username: user.username,
    realName: user.realName || '',
    email: user.email || '',
    phone: user.phone || '',
    role: user.role,
    status: user.status,
    password: ''
  })
  showAddDialog.value = true
}

const resetUserForm = () => {
  editingUser.value = null
  userFormRef.value?.resetFields()
  Object.assign(userForm, {
    username: '',
    realName: '',
    email: '',
    phone: '',
    role: '',
    status: 'active',
    password: ''
  })
}

const saveUser = async () => {
  try {
    await userFormRef.value.validate()
    
    saving.value = true
    
    if (editingUser.value) {
      // 编辑用户
      const { password, ...updateData } = userForm
      await api.put(`/admin/users/${editingUser.value.id}`, updateData)
      ElMessage.success('用户更新成功')
    } else {
      // 创建用户
      await api.post('/admin/users', userForm)
      ElMessage.success('用户创建成功')
    }
    
    showAddDialog.value = false
    loadUsers()
    loadStats()
    
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    saving.value = false
  }
}

const handleCommand = async (command, user) => {
  switch (command) {
    case 'enable':
    case 'disable':
      await toggleUserStatus(user)
      break
    case 'resetPassword':
      await resetUserPassword(user)
      break
    case 'delete':
      await deleteUser(user)
      break
  }
}

const toggleUserStatus = async (user) => {
  try {
    const action = user.status === 'active' ? '禁用' : '启用'
    await ElMessageBox.confirm(`确定要${action}用户 "${user.username}" 吗？`, '确认操作')
    
    const newStatus = user.status === 'active' ? 'disabled' : 'active'
    await api.put(`/admin/users/${user.id}/status`, { status: newStatus })
    
    ElMessage.success(`用户${action}成功`)
    loadUsers()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const resetUserPassword = async (user) => {
  try {
    await ElMessageBox.confirm(`确定要重置用户 "${user.username}" 的密码吗？`, '确认操作')
    
    const response = await api.put(`/admin/users/${user.id}/reset-password`)
    const newPassword = response.data.data.password
    
    await ElMessageBox.alert(`新密码：${newPassword}`, '密码重置成功', {
      confirmButtonText: '确定',
      type: 'success'
    })
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
    }
  }
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复！`, '确认删除', {
      type: 'warning'
    })
    
    await api.delete(`/admin/users/${user.id}`)
    ElMessage.success('用户删除成功')
    loadUsers()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const batchEnable = async () => {
  try {
    await ElMessageBox.confirm(`确定要启用选中的 ${selectedUsers.value.length} 个用户吗？`, '确认操作')
    
    const userIds = selectedUsers.value.map(user => user.id)
    await api.put('/admin/users/batch-status', { userIds, status: 'active' })
    
    ElMessage.success('批量启用成功')
    loadUsers()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败')
    }
  }
}

const batchDisable = async () => {
  try {
    await ElMessageBox.confirm(`确定要禁用选中的 ${selectedUsers.value.length} 个用户吗？`, '确认操作')
    
    const userIds = selectedUsers.value.map(user => user.id)
    await api.put('/admin/users/batch-status', { userIds, status: 'disabled' })
    
    ElMessage.success('批量禁用成功')
    loadUsers()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败')
    }
  }
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复！`, '确认删除', {
      type: 'warning'
    })
    
    const userIds = selectedUsers.value.map(user => user.id)
    await api.delete('/admin/users/batch', { data: { userIds } })
    
    ElMessage.success('批量删除成功')
    loadUsers()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const exportUsers = async () => {
  try {
    const response = await api.get('/admin/users/export', {
      params: filterForm,
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `用户数据_${formatDate(new Date(), 'YYYY-MM-DD')}.xlsx`
    link.click()
    
    window.URL.revokeObjectURL(url)
    ElMessage.success('数据导出成功')
    
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  loadStats()
  loadUsers()
})
</script>

<style scoped>
.user-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  margin-left: 20px;
}

.stats-row {
  margin-bottom: 24px;
}

.stats-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.stats-icon {
  font-size: 32px;
  opacity: 0.3;
  color: #409eff;
}

.filter-card,
.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.real-name {
  font-size: 12px;
  color: #909399;
}

.activity-count {
  font-weight: 600;
  color: #409eff;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.user-detail {
  text-align: center;
}

.detail-avatar {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    margin-left: 0;
    flex-direction: column;
  }
  
  .stats-card {
    margin-bottom: 16px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .table-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .table-actions .el-button {
    width: 100%;
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
}
</style>